package com.webbase.control.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.webbase.control.common.annotation.CurrentUser;
import com.webbase.control.common.result.ResponseConstant;
import com.webbase.control.common.result.Result;
import com.webbase.control.dto.Router;
import com.webbase.control.dto.UserInfo;
import com.webbase.control.pojo.Resource;
import com.webbase.control.pojo.Role;
import com.webbase.control.pojo.User;
import com.webbase.control.service.ResourceService;
import com.webbase.control.service.RoleService;
import com.webbase.control.service.UserService;
import com.webbase.control.util.Constant;
import com.webbase.control.util.JwtComponent;
import com.webbase.control.util.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Api(value = "登录控制器")
@RequestMapping("/auth")
@RestController
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtComponent jwtComponent;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private MD5 md5;


    @ApiOperation(value = "登录")
    @PostMapping("/login")
    @CrossOrigin
    public Result<String> login(@RequestBody User loginUser, HttpServletRequest request) {
        String userAccount = loginUser.getUserAccount();
        String userPass = loginUser.getUserPassword();
        String userPassword = md5.encrypt(userPass);
        if (StringUtils.isEmpty(userAccount) || StringUtils.isEmpty(userPassword)) {
            return new Result<String>().error("参数错误");
        }
        //查询用户是否存在
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        User user = (User) valueOperations.get("user_" + userAccount);
        if (user == null) {
            QueryWrapper<User> ew = new QueryWrapper<>();
            ew.eq("user_account", userAccount);
            user = userService.getOne(ew);
            valueOperations.set("user_" + user.getUserAccount(), user);
        }
        if (!StringUtils.isEmpty(user)) {
            if (!user.getUserPassword().equals(userPassword)) {
                return new Result<String>().error("账号或密码错误");
            }
            if (user.getUserState() == 0) {
                return new Result<String>().error("账号已禁用");
            }
            if (user.getUserDelFlag() == 0) {
                return new Result<String>().error("账号已失效");
            }
        } else {
            return new Result<String>().error("用户不存在");
        }
        String token = jwtComponent.sign(user.getUserAccount(), user.getUserPassword(), Constant.ExpTimeType.WEB);
        Result<String> objectResult = new Result<>();
//        return new Result<String>().success().put(token);
        return  objectResult.success().put(token);
    }

    /**
     * 获取个人信息
     *
     * @return
     */
    @ApiOperation(value = "获取用户信息")
    @CrossOrigin
    @GetMapping("/user/info")
    @RequiresAuthentication
    public Result<UserInfo> userInfo(HttpServletRequest request, @CurrentUser User currentUser) {
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        UserInfo userInfo = new UserInfo();
        //放入用户角色
        userInfo.setUserInfo(currentUser);
        Role userRole = (Role) valueOperations.get("userRole_" + currentUser.getUserId());
        if (userRole == null) {
            userRole = roleService.queryUserRole(currentUser.getUserId());
            valueOperations.set("userRole_" + currentUser.getUserId(), userRole);
        }
        if (userRole == null) {
            System.out.println("不是吧阿sir,这个用户没有身份角色啊");
        }
        userInfo.setRoleName(userRole.getRoleName());
        //递归查询出用户菜单并执行操作
        List<Router> userPerm = (List<Router>) valueOperations.get("user_perm" + currentUser.getUserId());
        if (userPerm == null) {
            userPerm = resourceService.queryUserResource(currentUser.getUserId());
            valueOperations.set("user_perm" + currentUser.getUserId(), userPerm);
        }
        for (Router router : userPerm) {
            Set<String> set = null;
            Map<String, Object> pageMap = new HashMap<>();
            pageMap.put("title", router.getRouter());
            pageMap.put("breadcrumb", new HashSet<String>(Arrays.asList(router.getCrumb().split(","))));
            router.setPage(pageMap);
            //权限处理 目前只放permission
            Map<String, String> authMap = new HashMap<>();
            authMap.put("permission", router.getAuth());
            router.setAuthority(authMap);
            //是否显示处理
            router.setInvisible(router.getIfshow() == 1 ? false : true);
            if (router.getChildren() != null && router.getChildren().size() > 0) {
                parseRouter(router.getChildren());
            }
        }
        //菜单包括用户菜单和用户菜单权限
        List<Resource> perms = resourceService.queryUserPerm(currentUser.getUserId());
        Set<String> userAuth = new HashSet<>();
        for (Resource perm : perms) {
            userAuth.add(perm.getResourceAuth());
        }
        //将用户菜单转化为前端需要的格式
        List<Map> userTreePerm = new ArrayList<>();
        Map treeMap = new HashMap();
        treeMap.put("router", "root");
        treeMap.put("children", userPerm);
        userTreePerm.add(treeMap);
        userInfo.setPermission(userAuth);
        userInfo.setRouters(userTreePerm);
        return new Result<UserInfo>().success().put(userInfo);
    }

    /**
     * 菜单递归操作
     *
     * @return
     */
    private static void parseRouter(List<Router> routers) {
        for (Router router : routers) {
            //meta中的page属性
            Map<String, Object> pageMap = new HashMap<>();
            pageMap.put("title", router.getRouter());
            pageMap.put("breadcrumb", new HashSet<String>(Arrays.asList(router.getCrumb().split(","))));
            router.setPage(pageMap);
            //权限处理 目前只放permission
            Map<String, String> authMap = new HashMap<>();
            authMap.put("permission", router.getAuth());
            router.setAuthority(authMap);
            //是否显示处理
            router.setInvisible(router.getIfshow() == 1 ? false : true);
            if (router.getChildren() != null && router.getChildren().size() > 0) {
                parseRouter(router.getChildren());
            }
        }
    }


    @PostMapping("401")
    @RequiresAuthentication
    public Result<?> unauthorized() {
        return new Result<>().error(ResponseConstant.USER_NO_PERMITION);
    }


    @PostMapping("/logout")
    public Result<?> logOut(HttpServletRequest request) throws Exception {
        return new Result<>().success();
    }


}
